var relationships = context.getAvailableRelationships();
var REL_SUCCESS = null;
var REL_FAILURE = null;

relationships.forEach(function(rel) {
    if (rel.getName() === 'success') {
        REL_SUCCESS = rel;
    } else if (rel.getName() === 'failure') {
        REL_FAILURE = rel;
    }
});

/**
 * 辅助函数：获取并格式化当前日期为 'YYYY-MM-DD' 格式
 */
function getCurrentDateFormatted() {
    var today = new Date();
    var year = today.getFullYear();
    var month = today.getMonth() + 1;
    if (month < 10) {
        month = '0' + month;
    }
    var day = today.getDate();
    if (day < 10) {
        day = '0' + day;
    }
    return year + '-' + month + '-' + day;
}

var flowFile = session.get();
if (flowFile === null) {
    flowFile = session.create();
}

try {
    if (REL_SUCCESS === null) {
        throw new Error("在处理器的可用关系中找不到 'success' 关系。");
    }

    var jsonData = {
        "erpSysFlag": "0000",
        "bizContent": {
            "bankAccNo": "201000270605501",
            "queryBeginDate": "",
            "queryEndDate": "",
            "current": 1,
            "size": 100
        }
    };

    var currentDate = getCurrentDateFormatted();
    //测试
    jsonData.bizContent.queryBeginDate = "2021-01-01";
    jsonData.bizContent.queryEndDate = "2021-01-31";

    var jsonString = JSON.stringify(jsonData);

    // 关键修正：为了解决Nashorn引擎对 session.write 的方法签名歧义问题，
    // 我们必须显式地创建一个 org.apache.nifi.processor.io.OutputStreamCallback 的实例。
    flowFile = session.write(flowFile, new (Java.type('org.apache.nifi.processor.io.OutputStreamCallback'))({
        process: function(outputStream) {
            outputStream.write(jsonString.getBytes("UTF-8"));
        }
    }));

    session.transfer(flowFile, REL_SUCCESS);

} catch (e) {
    log.error('处理 JSON 并创建 FlowFile 时出错。', e);

    if (REL_FAILURE !== null) {
        session.transfer(flowFile, REL_FAILURE);
    } else {
        session.remove(flowFile);
    }
}